package algorithm_optimal_solution.TwoForkTree;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class MinDepthTree {

    static class Node{
        private int value;
        private Node left;
        private Node right;

        public Node(int value) {
            this.value = value;
        }

        public Node(int value, Node left, Node right) {
            this.value = value;
            this.left = left;
            this.right = right;
        }

        public int getValue() {
            return value;
        }

        public void setValue(int value) {
            this.value = value;
        }

        public Node getLeft() {
            return left;
        }

        public void setLeft(Node left) {
            this.left = left;
        }

        public Node getRight() {
            return right;
        }

        public void setRight(Node right) {
            this.right = right;
        }
    }

    public int minDepth(Node head,int level){
        if(head.getLeft() == null && head.getRight() == null){
            return level;
        }
        int depth = Integer.MAX_VALUE;
        if(head.getLeft() != null){
            depth = Math.min(minDepth(head.getLeft(),level + 1),depth);
        }
        if(head.getRight() != null){
            depth = Math.min(minDepth(head.getRight(), level + 1),depth);
        }
        return depth;
    }

    public void createTree(Node head, int[][] arr){
        int left = arr[head.getValue()][0];
        int right = arr[head.getValue()][1];
        if(left != 0){
            Node leftNode = new Node(left);
            head.setLeft(leftNode);
            createTree(leftNode,arr);
        }
        if(right != 0){
            Node rightNode = new Node(right);
            head.setRight(rightNode);
            createTree(rightNode,arr);
        }
    }

    public static void main(String[] args)throws IOException {
        MinDepthTree main = new MinDepthTree();
        BufferedReader scanner = new BufferedReader(new InputStreamReader(System.in));
        String[] values = scanner.readLine().split(" ");
        int len = Integer.parseInt(values[0]);
        Node root = new Node(Integer.parseInt(values[1]));
        int[][] arr = new int[len + 1][2];
        String[] numbers = scanner.readLine().split(" ");
        arr[root.getValue()][0] = Integer.parseInt(numbers[1]);
        arr[root.getValue()][1] = Integer.parseInt(numbers[2]);
        for (int i = 1; i < len; i++) {
            numbers = scanner.readLine().split(" ");
            int index = Integer.parseInt(numbers[0]);
            arr[index][0] = Integer.parseInt(numbers[1]);
            arr[index][1] = Integer.parseInt(numbers[2]);
        }
        StringBuilder sb = new StringBuilder();
        main.createTree(root, arr);
        System.out.println(main.minDepth(root,1));;
    }
}
